package run.iget.framework.common.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollUtil;
import run.iget.framework.common.entity.TreeIdEntity;

/**
 * 代码千万行，注释第一行，注释不规范，迭代两行泪
 * ---------------类描述-----------------
 * 树形结构工具类，如：菜单、机构等
 * ---------------类描述-----------------
 * @author 大周
 * @date 2023/7/20 19:11
 */
public class TreeUtils {

    /**
     * 默认根节点id
     */
    private static final Long DEFAULT_ROOT_ID = 0L;

    /**
     * 根据pid，构建树节点
     */
    public static <T extends TreeIdEntity> List<T> build(List<T> treeNodes, Long pid) {
        if (Objects.isNull(pid)) {
            return treeNodes;
        }

        List<T> treeList = new ArrayList<>();
        for (T treeNode : treeNodes) {
            if (pid.equals(treeNode.getPid())) {
                treeList.add(findChildren(treeNodes, treeNode));
            }
        }

        return treeList;
    }

    /**
     * 查找子节点
     */
    private static <T extends TreeIdEntity> T findChildren(List<T> treeNodes, T rootNode) {
        for (T treeNode : treeNodes) {
            if (rootNode.getId().equals(treeNode.getPid())) {
                if (Objects.isNull(rootNode.getChildren())) {
                    rootNode.setChildren(new ArrayList<>());
                }
                rootNode.getChildren().add(findChildren(treeNodes, treeNode));
            }
        }
        return rootNode;
    }

    /**
     * 构建树节点
     */
    public static <T extends TreeIdEntity> List<T> build(List<T> treeNodes) {
        if (CollUtil.isEmpty(treeNodes)) {
            return null;
        }
        return build(treeNodes, DEFAULT_ROOT_ID);
    }

}
